import config from '@/common/config'
let baseURL = config.cesuUrl;
let aiURL = config.aiUrl;
let shenShaUrl = config.shenShaUrl;

let isMagg = true

export const post = (url,data,showLoading = true) => {
  return apiRequest({url,data,method:'POST',showLoading})
}

export const get = (url,data) => {
  return apiRequest({url,data,method:'GET'})
}
export const apiRequest = (options) =>{
	return new Promise((resolve,reject)=>{
    if(options.showLoading){
      uni.showLoading({
        title:'加载中'
      })
    }
		let header = {
			// "content-type": "application/x-www-form-urlencoded",
			"content-type": "application/json",
			'token':uni.getStorageSync("token") || '',
		};
		if(options.data && options.data.userId){
			header.userId = options.data.userId;
		}
		let requestUrl = "";
		// 判断是否AI接口
		if(options.data && options.data.isAi){
			requestUrl = aiURL + options.url
			delete options.data.isAi;
		}else if(options.data && options.data.isShenSha){ //是否获取八字,  神煞接口
			header["content-type"] = "application/x-www-form-urlencoded";
			requestUrl = shenShaUrl + options.url;
			delete options.data.isShenSha;
			console.log('shenShaUrl',header)
		}else{
			requestUrl = baseURL + options.url
		}
		console.log('出来了',requestUrl)
		uni.request({
			url: requestUrl, //接口地址：前缀+方法中传入的地址
			method: options.method || 'POST',
			data: options.data || {},
			header,
			success:(response)=> {
        	uni.hideLoading();
				const status = Number(response.data.code ?? (response.data.detail && response.data.detail.code)) || 0;
				// const status = Number(response.data.code || response.data.detail && response.data.detail.code)
				const message = response.data.message || response.data.detail && response.data.detail.message || '网络异常';
				// 登录过期
				if (status === 202) {
					if (isMagg) {
						isMagg = false;
						uni.showToast({
							icon:'error',
							mask:true,
							title: '登录过期',
						})
						uni.removeStorageSync('token');
						uni.removeStorageSync('userinfo');
						console.log('登录过期')
						// 如果接口报401错误，  就阻塞所有定时器
						setTimeout(()=>{
							isMagg = true
							uni.switchTab({
								url: '/pages/index/index'
							});
						},1000)
					}
				}
				// const isResultValid =
				// 	(typeof response.data.result === "string" && response.data.result.trim() !== "") ||
				// 	(typeof response.data.result === "object" && response.data.result !== null && Object.keys(response.data.result).length > 0);
				if(status != 1){
					if (isMagg) {
						setTimeout(() => {
							uni.showToast({
								title: message,
								icon: 'none',
								duration: 1500
							});
						}, 100)
						isMagg = false
						setTimeout(() => {
							isMagg = true
						}, 1000)
					}
				}
				// 如果不满足上述判断就输出数据
				resolve(response.data)
			},
			// 这里的接口请求，如果出现问题就输出接口请求失败
			fail: (err) => {
        uni.hideLoading();
				uni.showToast({
					title:"请求失败",
					icon:"none"
				})
        
				reject(err)
			}
		})
	})
}
export const uploadFile = (url,params) => {
  // 如果上传的图片或者视频大于判断提示不让上传
  if(params.size > 26214400){ //25M
  // if(params.size > 31457280){ //30M
    uni.showToast({
      mask:true,
      icon:'error',
      title:`上传的${params.type == 'image' ? '图片' : '视频'}不能超过25M,请重新上传···`
    })
    // 模拟报错信息，要不然上传图片的页面会报错，找不到code
    let info = {code : 0}; 
    return info
  }
  return apiUploadFile({url,filePath:params.filePath})
}
export const apiUploadFile = (options) =>{
  uni.showLoading({
  	title: '上传中...',
  	mask: true
  })
	console.log('ssssss',options);
	return new Promise((resolve,reject)=>{
		uni.uploadFile({
			url: baseURL + options.url, //接口地址：前缀+方法中传入的地址
			filePath: options.filePath,
		  	header:{
				'token':uni.getStorageSync("token") || '',
		  	},
			name: 'file',
			formData: {
				id: JSON.parse(uni.getStorageSync('userinfo')).id,
			},
			success:(response)=> {
        uni.hideLoading()
				const res = JSON.parse(response.data)
				const status = Number(res.code)
				const message = res.message || '未知错误'
				console.log('上传成功',res)
				if (status !== 1) {
					if (isMagg) {
						uni.showToast({
							title: message,
							icon: 'error',
							duration: 1500
						});
						isMagg = false
						setTimeout(() => {
							isMagg = true
						}, 1000)
					}
				}
				// 如果不满足上述判断就输出数据
				resolve(res)
			},
			// 这里的接口请求，如果出现问题就输出接口请求失败
			fail: (err) => {
        uni.hideLoading()
				uni.showToast({
					title:"请求接口失败",
					icon:"none"
				})
				reject(err)
			}
		})
	})
}
